import * as dotenv from "dotenv";
import sendWebhookMessage from "./utils/sendWebhookMessage";
import greetings from "./utils/greetings";
import getTime from "./utils/getTime";
import isWorkday from "./utils/isWorkday";
import notice from "./utils/notice";

// 加载 .env 文件
dotenv.config({path: ".env"});

// 从 .env 文件中读取配置
const webhookUrl = process.env.WEBHOOK_URL || "";
const secret = process.env.SECRET_KEY || "";
const holidayApi = process.env.HOLIDAY_API || "";
const weatherApi = process.env.WEATHER_API || "";
const city = process.env.CITY || "";
const morning_time = process.env.MORNING_TIME || "08:00";
const evening_time = process.env.EVENING_TIME || "17:00";

if (!webhookUrl || !secret) {
    console.error("Error: WEBHOOK_URL 或 SECRET_KEY 未在 .env 文件中配置。");
    process.exit(1);
}

enum Mode {
    Punch = "punch",
    Restart = "restart",
}

// 动态计算延迟时间
const calculateDelay = async (hour: number, minute: number, mode: Mode): Promise<number> => {
    const now = new Date();
    const targetTime = new Date();

    targetTime.setHours(hour, minute, 0, 0);

    if (now > targetTime) {
        if (mode === Mode.Restart) {
            // 如果目标时间已经过去，调整到第二天的目标时间
            targetTime.setDate(targetTime.getDate() + 1);

            console.log(
                `${getTime()}`,
                `调整新的目标时间为: ${targetTime.toLocaleString("zh-CN", {
                    timeZone: "Asia/Shanghai",
                    year: "numeric",
                    month: "2-digit",
                    day: "2-digit",
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit",
                })}`
            )
        } else {
            return -1
        }
    } else if (mode === Mode.Punch && !await isWorkday(targetTime, holidayApi)) {
        console.log(
            `${getTime()}`,
            `今天不需要上班，跳过今天打卡提醒`
        )
        return -1
    }

    // 返回延迟时间（毫秒），加 500 毫秒余地
    return targetTime.getTime() - now.getTime() + 500;
};

// 定时提醒（多次提醒）
function scheduleRepeatedReminders(
    webhookUrl: string,
    secret: string,
    isMorning: boolean,
    repeats: number,
    intervalMinutes: number,
    weatherApi?: string,
    city?: string,
) {
    const sendReminder = async (count: number) => {
        if (count > repeats) return;

        const timestamp = Math.round(Date.now() / 1000).toString();
        const message = await greetings(isMorning, count, weatherApi, city);
        sendWebhookMessage(webhookUrl, timestamp, message, secret);

        setTimeout(() => sendReminder(count + 1), intervalMinutes * 60 * 1000);
    };

    sendReminder(1);
}

// 设置定时任务
// 设置定时任务
async function scheduleReminder(
    webhookUrl: string,
    secret: string,
    morningTime: string = "8:00",
    eveningTime: string = "17:00",
    morningRepeatTimes: number = 1,
    eveningRepeatTimes: number = 1,
    morningRepeatIntervalMinutes: number = 5,
    eveningRepeatIntervalMinutes: number = 5,
    weatherApi?: string,
    city?: string,
) {
    console.log('\n',
        getTime(),
        "打卡提醒任务启动!"
    );

    const settings = [
        {Parameter: "上班定时", Value: morningTime},
        {Parameter: "上班定时提醒次数", Value: morningRepeatTimes},
        {Parameter: "上班定时提醒间隔（分钟）", Value: morningRepeatIntervalMinutes},
        {Parameter: "========================", Value: "========"},
        {Parameter: "下班定时", Value: eveningTime},
        {Parameter: "下班定时提醒次数", Value: eveningRepeatTimes},
        {Parameter: "下班定时提醒间隔（分钟）", Value: eveningRepeatIntervalMinutes},
    ];

    console.table(settings);

    const [morningHour, morningMinute] = morningTime.split(":").map(Number);
    const [eveningHour, eveningMinute] = eveningTime.split(":").map(Number);

    const morningDelay = await calculateDelay(morningHour, morningMinute, Mode.Punch);
    const eveningDelay = await calculateDelay(eveningHour, eveningMinute, Mode.Punch);

    // 早上提醒任务
    if (morningDelay !== -1) {
        notice(morningDelay, "上班");
        setTimeout(() => {
            scheduleRepeatedReminders(webhookUrl, secret, true, morningRepeatTimes, morningRepeatIntervalMinutes, weatherApi, city);
        }, morningDelay);
    }

    // 晚上提醒任务
    if (eveningDelay !== -1) {
        notice(eveningDelay, "下班");
        setTimeout(() => {
            scheduleRepeatedReminders(webhookUrl, secret, false, eveningRepeatTimes, eveningRepeatIntervalMinutes, weatherApi, city);
        }, eveningDelay);
    }

    // 每天定时重新启动提醒任务
    const nextDayDelay = await calculateDelay(0, 0, Mode.Restart); // 每天凌晨 00:00 重置任务
    setTimeout(() => {
        scheduleReminder(webhookUrl, secret, morningTime, eveningTime, morningRepeatTimes, eveningRepeatTimes, morningRepeatIntervalMinutes, eveningRepeatIntervalMinutes);
    }, nextDayDelay);
}


// 启动任务
(async () => {
    await scheduleReminder(webhookUrl, secret, morning_time, evening_time, 1, 1, 5, 5, weatherApi, city);
})()